package services;

import dao.Location_Repository;
import models.DatabaseExecutionContext;
import models.Location_T_Entity;
import models.VehGpsData_P_Entity;
import models.VehStopLog_V_Entity;
import play.db.jpa.JPAApi;

import javax.inject.Inject;
import java.util.List;
import java.util.concurrent.CompletionStage;

import static java.util.concurrent.CompletableFuture.supplyAsync;

public class Location_Repository_JPA implements Location_Repository {


    private final JPAApi jpaApi;
    private final DatabaseExecutionContext executionContext;

    @Inject
    public Location_Repository_JPA(JPAApi jpaApi, DatabaseExecutionContext executionContext) {
        this.jpaApi = jpaApi;
        this.executionContext = executionContext;
    }

    @SuppressWarnings("unchecked")
    @Override
    public CompletionStage<List<Location_T_Entity>>  getLocationByID (String applyInId)
    {
        return supplyAsync(() -> {
            return jpaApi.withTransaction(entityManager -> {

                String strSql = "select * from v_LoactionInfo where fd_ApplyID = '" + applyInId+ "' order by fd_ModifiedDate asc";
                return entityManager.createNativeQuery(strSql, Location_T_Entity.class).getResultList();

                //return entityManager.createQuery("select c from ApplyInfo_T_Entity c ", ApplyInfo_T_Entity.class).getResultList();

//                List<Location_T_Entity> resultList = entityManager
//                        .createQuery(
//                                "select l from Location_T_Entity l where l.fd_ApplyID=:applyInId order by l.fdRowId",
//                                Location_T_Entity.class)
//                        .setParameter("applyInId", applyInId).getResultList();
//                //String strSql = "select * from dbo.f_TableApplyInfo(GETDATE(),'" + EndDate + "','" + ConTractNum + "','" + Deliveryid + "','"+ KHMC +"','" + HWMC + "','"+ Status +"') as ApplyInfo";
//                return resultList;
            });
        }, executionContext);
    }

    @SuppressWarnings("unchecked")
    public CompletionStage<List<Location_T_Entity>>  stopLogById (String ApplyID)
    {
        return supplyAsync(() -> {
            return jpaApi.withTransaction(entityManager -> {

                String strSql = "select * from v_VehStopLog where fd_ApplyID = '" + ApplyID+ "' order by fd_RecordDate asc";
                return entityManager.createNativeQuery(strSql, VehStopLog_V_Entity.class).getResultList();


            });
        }, executionContext);
    }

    @Override
    public CompletionStage<List<Location_T_Entity>> getGPSDatabyPoundNo(String poundNo, String dataType) {
        return supplyAsync(() -> {
            return jpaApi.withTransaction(entityManager -> {

                String strSql = "exec p_GetVehGpsData '"+poundNo+"','"+dataType+"'";
                return entityManager.createNativeQuery(strSql, VehGpsData_P_Entity.class).getResultList();


            });
        }, executionContext);
    }
}
